<template>
  <el-container>
    <el-aside>
      <el-input
              class="searchDepartment"
              placeholder="搜索姓名、工号、用户名"
              prefix-icon="el-icon-search"
              v-model="input2">
      </el-input>
      <div class="departmentList">
        <el-tree
                :data="data"
                node-key="id"
                icon-class="el-icon-caret-right"
                default-expand-all
                :expand-on-click-node="false"
                class="el-treeItem">
          <div class="custom-tree-node" slot-scope="{ node, data }">
            <span @click="tableTitleFunc(node)">{{ node.label }}</span>
              <edit-department  v-if="node.level == 1" :events="dropMenuEvents" :data="{node,data}" @addDepartment="openDepartment"/>
              <edit-department  v-if="node.level == 2 && data.id != 2" :data="{node,data}" @addDepartment="openDepartment" @deleteDepartment="deleteDepartment"
              @editDepartment="editDepartment" @chooseMember="chooseMember" @moveDepartment="moveDepartment"/>
          </div>
        </el-tree>
      </div>
    </el-aside>
    <el-main>
      <member-table :tableTitle = "tableTitle" :tableData = "tableData"></member-table>
      <el-dialog
              title="添加子部门"
              :visible.sync="AddDialog"
              width="500px"
              center
              :modal='false'>
        <el-form ref="form" label-width="80px">
          <el-form-item label="部门名称">
            <el-input v-model="sonDepartmentName" placeholder="请输入部门名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addDepartment()">确定</el-button>
            <el-button @click="AddDialog = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog
              title="编辑部门"
              :visible.sync="EditDialog"
              width="500px"
              center
              :modal='false'>
        <el-form ref="form" label-width="80px">
          <el-form-item label="部门名称">
            <el-input  v-model="currentDepartment"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="alertDepartment()">确定</el-button>
            <el-button @click="EditDialog = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog
              title="选择成员"
              :visible.sync="ChooseMemberDialog"
              width="1000px"
              center
              :modal='false'>
        <div style="text-align: center">
          <el-transfer
                  style="text-align: left; display: inline-block"
                  v-model="chooseMemberTransfer"
                  filterable
                  :titles="['未分配部门成员', '已选择成员']"
                  :button-texts="['到左边', '到右边']"
                  :format="{
                          noChecked: '${total}',
                          hasChecked: '${checked}/${total}'
                        }"
                  @change="handleChange"
                  :data="member">
            <span slot-scope="{ option }">{{ option.id }} - {{ option.label }}</span>
          </el-transfer>
        </div>
        <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="alertChooseMember()" style="margin-top: 10px;">确定</el-button>
                    <el-button @click="ChooseMemberDialog = false">取消</el-button>
                    </span>
      </el-dialog>
      <el-dialog
              title="移动部门"
              :visible.sync="moveDepartmentDialog"
              width="500px"
              center
              :modal='false'>
            <el-select v-model="department" filterable placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in departments"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="removeDepartment()">确定</el-button>
              <el-button @click="moveDepartmentDialog = false">取消</el-button>
            </span>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
  import editDepartment from "../../components/content/editDepartment";
  import SearchMember from "../../components/common/searchMember";
  import MemberTable from "../../components/content/memberTable";
  const axios = require('axios');
  let id = 3;
  let tempData ;

  export default {
  name: "Member",
    components: {
      MemberTable,
      SearchMember,
      editDepartment},
    data() {
      const data = [{
        id: 1,
        label: '',
        department_id : 0,
        children: [{
          id: 2,
          label: '未分配部门',
        },]
      }];
      return {
        sonDepartmentName:'',
        moveDepartments:'',
        department:'',
        departments:[],
        input2: "",
        newDepartment:"",
        department_id:0,
        AddDialog: false,
        EditDialog: false,
        ChooseMemberDialog: false,
        moveDepartmentDialog: false,
        currentDepartment: "",
        currentDepAdmin: "",
        currentDepNum: "",
        tableTitle: '',
        tableData:[],
        treeId: 0,
        data: JSON.parse(JSON.stringify(data)),
        dropMenuEvents: [
          { label: '添加子部门', funcName: 'addDepartment'},
         ],
        member: [],
        chooseMemberTransfer: [1],
    }
    },
    created() {
      setTimeout(() => {
        this.$parent.$parent.CheckEnterprise();
        this.$parent.$parent.ToShow();
      },100)
    },
    mounted() {
      this.$axios.all([
        axios.post('/getEnterPriseName', {'enterprise_id': window.localStorage.getItem("enterprise_id")}),
        axios.post('/getEnterpriseUser',{'id': window.localStorage.getItem("enterprise_id")}),

      ]).then(this.$axios.spread((res1,res2) => {
        this.tableTitle = res1.data.enterprise_name;
        this.data[0].label = res1.data.enterprise_name;
        // console.log(res2);
        for(let i = 0;i < res2.data[0].departments.length;i++){
          this.newDepartment = res2.data[0].departments[i].depart_name;
          this.department_id = res2.data[0].departments[i].department_id;
          if(res2.data[0].departments[i].father_id != 0){
            for(let j = 0;j < res2.data[0].departments.length;j++){
              if(res2.data[0].departments[j].department_id == res2.data[0].departments[i].father_id){
                this.append(this.data[0].children[j+1]);
              }
            }
          }else{
            this.append(this.data[0]);
          }
        }

      }))
    },
    methods:{
      append(data) {
        const newChild = { id: id++, label: this.newDepartment, department_id: this.department_id,children: [] };
        if (!data.children) {
          this.$set(data, 'children', []);
        }
        data.children.push(newChild);
      },

      handleChange(value, direction, movedKeys) {
        console.log(value, direction, movedKeys);
      },

      tableTitleFunc(node){
        this.tableTitle = node.label;
        if(node.id == 1){
          axios.post('/getAllUser',{'id': window.localStorage.getItem("enterprise_id")}).then(res => {
            this.tableData = res.data;
          })
        }else if(node.id == 2){
          axios.post('/getNoDepartmentUser',{'id': window.localStorage.getItem("enterprise_id")}).then(res => {
            this.tableData = res.data;
          })
        }else{
          axios.post('/getDepartmentUser',{'enterpriseId': window.localStorage.getItem("enterprise_id"),'id':node.data.department_id}).then(res => {
            this.tableData = res.data;
          })
        }
      },

      openDepartment({node,data}){
        tempData = data;
        this.AddDialog = true;
      },

      moveDepartment({node,data}){
        axios.post("/getMoveDepartment",{"id":window.localStorage.getItem("enterprise_id")}).then(res => {
          this.departments = res.data;
        })
        this.moveDepartmentDialog = true;
      },

      removeDepartment(){
        this.moveDepartmentDialog = false;
      },

      addDepartment(){
        this.AddDialog = false;
        this.append(tempData);
      },

      alertDepartment() {
        this.EditDialog = false;
      },

      alertChooseMember() {
        this.ChooseMemberDialog = false;
      },

      remove(node, data) {
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
      },

      chooseMember({node,data}) {
        axios.post("/getNoDepartmentUser",{"id":window.localStorage.getItem("enterprise_id")}).then(res => {
          console.log(res);
          for (let i = 0; i < res.data.length; i++) {
            this.member.push({
              id: res.data[i].id,
              label: res.data[i].name,
            });
          }
        });
        this.ChooseMemberDialog = true;
      },

      handleChange(value, direction, movedKeys) {
        console.log(value, direction, movedKeys);
      },


      deleteDepartment({node,data}) {
        this.$confirm('确定删除部门' +  data.label + '?', '删除部门', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          modal: false,
        }).then(() => {
          this.remove(node, data)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      editDepartment({node,data}){
        this.currentDepartment = data.label;
        this.EditDialog = true;
      }
    },
  }
</script>

<style scoped>
  .el-aside {
    text-align: center;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .searchDepartment {
    margin-top: 20px;
    width:90%;
  }

  .departmentList {
    margin-top: 20px;
    margin-left: 15px;
    overflow: auto;
    width: 90%;
  }

</style>
